﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Data;

namespace QuanLyKho.DKChung
{
    public partial class DKChung_DkHinhAnh : Form
    {
        public static string MaID = "0";
        public static int Loai = 0;
        public bool update = false;
        private byte[] _content;

        public DKChung_DkHinhAnh()
        {
            InitializeComponent();
            //cbbLoai.SelectedIndex = 0;
            LoadData();
        }

        public void LoadData()
        {
            if (MaID != "0")
            {
                var data = DataAll.SelectAll("DkChung_HinhAnh", "*", " WHERE IDHinhAnh=" + MaID);
                txtMaAnh.Text = data.Rows[0]["MaAnh"].ToString();
                txtTenAnh.Text = data.Rows[0]["TenAnh"].ToString();
                dtNgayTao.Value = Convert.ToDateTime(data.Rows[0]["NgayTao"].ToString());
                //cbbLoai.SelectedIndex = Convert.ToInt32(data.Rows[0]["Loai"]);
                _content = (byte[])data.Rows[0]["Anh"];
                if (_content != null)
                {
                    Image newImage;
                    using (var ms = new MemoryStream(_content, 0, _content.Length))
                    {
                        ms.Write(_content, 0, _content.Length);
                        newImage = Image.FromStream(ms, true);
                    }

                    pbAnhKho.Image = newImage;
                }
                else
                {
                    pbAnhKho.Image = null;
                }
                txtGhiChu.Text = data.Rows[0]["GhiChu"].ToString();
            }
        }

        public byte[] FileToByteArray(string fileName)
        {
            byte[] buffer = null;
            try
            {
                // Open file for reading 
                var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                // attach filestream to binary reader 
                var binaryReader = new BinaryReader(fileStream);
                // get total byte length of the file 
                long totalBytes = new FileInfo(fileName).Length;
                // read entire file into buffer 
                buffer = binaryReader.ReadBytes((Int32)totalBytes);
                // close file reader 
                fileStream.Close();
                fileStream.Dispose();
                binaryReader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return buffer;
        }

        public Image resizeImage(Image imgToResize, Size size)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();
            return (Image)b;
        }

        private void pbAnhKho_Click(object sender, EventArgs e)
        {
            var openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image file|*.jpg;*.jpeg;*.png";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var fileInfo = new FileInfo(openFileDialog.FileName);
                if (fileInfo.Exists)
                {
                    pbAnhKho.BackgroundImage = null;
                    pbAnhKho.Image = resizeImage(new Bitmap(openFileDialog.FileName), new Size(500, 500));
                    txtTenAnh.Text = fileInfo.Name;
                    var converter = new ImageConverter();
                    //_content = FileToByteArray(openFileDialog.FileName);
                    _content = fileInfo.Length >= 200000 ? (byte[])converter.ConvertTo(resizeImage(new Bitmap(openFileDialog.FileName), new Size(500, 500)), typeof(byte[])) : FileToByteArray(openFileDialog.FileName);
                    /*_fileName = fileInfo.Name;
                    _filetype = fileInfo.Extension;*/
                }
            }
        }

        public void ResetControl()
        {
            txtMaAnh.Text = string.Empty;
            txtTenAnh.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
            pbAnhKho.Image = null;
        }

        private void bntLuuLai_Click(object sender, EventArgs e)
        {
            if (update)
            {
                string message = DataAll.UpdateImage(Convert.ToInt32(MaID), txtMaAnh.Text, txtTenAnh.Text
                    , dtNgayTao.Value, _content, Convert.ToByte(Loai), txtGhiChu.Text);
                MessageBox.Show(message.Equals("success") ? "Sửa hình ảnh thành công" : message, "Message",
                                MessageBoxButtons.OK,
                                message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                Close();
            }
            else
            {
                var dataCheck = DataAll.SelectAll("DkChung_HinhAnh", "MaAnh", " WHERE MaAnh =N'" + txtMaAnh.Text + "' AND Loai=" + Loai.ToString());
                if (dataCheck.Rows.Count == 0)
                {
                    string message = DataAll.InsertImage(txtMaAnh.Text, txtTenAnh.Text, dtNgayTao.Value,
                                                         _content, Convert.ToByte(Loai), txtGhiChu.Text);
                    MessageBox.Show(message.Equals("success") ? "Thêm hình ảnh thành công" : message, "Message",
                                    MessageBoxButtons.OK,
                                    message.Equals("success") ? MessageBoxIcon.Information : MessageBoxIcon.Error);
                    if (message.Equals("success"))
                    {
                        ResetControl();
                    }
                }
                else
                {
                    MessageBox.Show("Nhập trùng mã ảnh", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void bntThoat_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
